<template>
<div class="table-container">
  <!-- 表格上方操作 -->
  <Row class="table-operation">
    <!-- 操作按钮 -->
    <Col span="12">
    <ButtonGroup class="btn-list" shape="circle">
      <template v-for="item in operateLabels">
        <Button v-if="item.Hidden !==true" :key="item.Id" size="small" type="default" @click="emit(item.Event, selectRows)" :icon="item.Icon">
                {{item.Name | btnName }}
            </Button>
      </template>
    </ButtonGroup>
    <slot name="select"></slot>
    <span v-if="operateLabels.length == 0">&nbsp;</span>
    </Col>
    <!-- 搜索及导出数据 -->
    <Col span="12">
    <Row type="flex" justify="end">
      <Col span="24">

      <Button-group class="btn-list" shape="circle" style="float:right;">
        <Button
                  type="default"
                  @click="refresh">
                  刷新
              </Button>
        <Button
                  type="default"  icon="ios-download-outline"
                  @click="exportData(1)">
                  导出
              </Button>
        <Button
                  type="default"  icon="ios-download-outline"
                  @click="exportData(2)">
                  导出全部
              </Button>
      </Button-group>
      <Input
            ref="searchtxt"
            v-model.trim="searchKey"
            icon="md-search"
            style="display:inline-block; width:200px;float:right;"
            placeholder="请输入..."

            @on-enter="search"/>
          </Col>
    </Row>
    </Col>
  </Row>
  <!-- table -->
  <Row>
    <Col span="24">
    <Table class="table" ref="table" :data="currentRows" :columns="columnList" :stripe="stripe" :border="border" :show-header="showHeader" :width="width" :height="height" :loading="loading" :disabled-hover="disabledHover" :highlight-row="highlightRow" :size="size" :no-data-text="noDataText" :no-filtered-data-text="noFilteredDataText" @on-current-change="onCurrentChange" @on-select="onSelect" @on-select-cancel="onSelectCancel" @on-select-all="onSelectAll" @on-select-all-cancel="onSelectAllCancel" @on-selection-change="onSelectionChange" @on-sort-change="onSortChange" @on-filter-change="onFilterChange" @on-row-click="onRowClick" @on-row-dblclick="onRowDblclick" @on-expand="onExpand" />
    <div v-if="pager" style="margin: 10px;overflow: hidden">
      <div style="float: right;">
        <Page :total="pagedata.total" :current="pagedata.current" :page-size="pagedata.pageSize" :page-size-opts="pagedata.pageSizeOpts" show-elevator show-total show-sizer @on-change="changePage" @on-page-size-change="changeSize" />
      </div>
    </div>
    </Col>
  </Row>
</div>
</template>

<script>
import { oneOf, deepCopy, checkAccess } from '@/common/utils';
import { mapMutations, mapGetters, mapState } from 'vuex';
export default {
  name: 'BaseTable',
  data () {
    return {
      searchKey: '',
      columnList: [],
      pageSize: 10,
      pagedata: {
        total: this.total,
        current: 1,
        pagesize: 10,
        page: 1,
        searchKey: '',
        sortby: '',
        order: ''
      },
      selectRows: []
    };
  },
  watch: {
    'pagedata.current' (newVal, oldVal) {
      // console.log(newVal);
      if (this.pager) {
        if (this.front) {
        }
      }
    },
    'pagedata.pagesize' (newVal, oldVal) {},
    total (newVal) {
      this.pagedata.total = newVal;
    }
  },
  props: {
    // 分页参数
    // 是否需要分页，默认不分页
    pager: {
      type: Boolean,
      default: () => false
    },
    // 后端分页
    back: {
      type: Boolean,
      default: () => false
    },
    // 前端分页
    front: {
      type: Boolean,
      default: () => false
    },
    total: {
      type: Number,
      default: () => 0
    },
    data: {
      type: Array,
      default () {
        return [];
      }
    },
    columns: {
      type: Array,
      default () {
        return [];
      }
    },
    size: {
      validator (value) {
        return oneOf(value, ['small', 'large', 'default']);
      },
      default () {
        return !this.$IVIEW || this.$IVIEW.size === ''
          ? 'default'
          : this.$IVIEW.size;
      }
    },
    width: {
      type: [Number, String]
    },
    height: {
      type: [Number, String]
    },
    stripe: {
      type: Boolean,
      default: false
    },
    border: {
      type: Boolean,
      default: false
    },
    showHeader: {
      type: Boolean,
      default: true
    },
    highlightRow: {
      type: Boolean,
      default: false
    },
    rowClassName: {
      type: Function,
      default () {
        return '';
      }
    },
    context: {
      type: Object
    },
    noDataText: {
      type: String
    },
    noFilteredDataText: {
      type: String
    },
    disabledHover: {
      type: Boolean
    },
    loading: {
      type: Boolean,
      default: false
    },
    op: {
      type: Boolean,
      default: false
    },
    ck: {
      type: Boolean,
      default: false
    }
  },
  filters: {
    btnName: function (value) {
      if (typeof value === 'string') {
        let strarray = value.split('-');
        if (strarray.length !== 2) {
          return value;
        }
        return strarray[1];
      }
      return value;
    }
  },
  computed: {
    ...mapGetters({
      operateLabels: 'getLabels'
    }),
    currentRows () {
      if (this.pager) {
        if (this.front) {
          // console.log(this.pagedata);
          let from = this.pagedata.pagesize * (this.pagedata.current - 1);
          let to = from + this.pagedata.pagesize;
          // console.log(from, to);
          return this.data.slice(from, to);
        }
        if (this.back) {
          return this.data;
        }
      }
      return this.data;
    }
    // pagedata () {
    //   return {
    //     total: this.total,
    //     pagesize: this.pageSize,
    //     page: this.current,
    //     searchKey: this.searchKey,
    //     sortby: this.sortby,
    //     order: this.order
    //   };
    // }
  },
  methods: {
    emit (name, params1, params2, params3) {
      this.$emit(name, params1, params2, params3);
    },
    exportData (type) {
      if (type === 1) {
        let all = {
          pagesize: -1,
          page: 1,
          searchKey: '',
          sortby: this.sortby,
          order: this.order
        };
        this.$emit('search', all);
        setTimeout(() => {
          this.$refs.table.exportCsv({
            filename: '原始数据',
            quoted: true
            //            columns: this.columns.filter((col, index) => index < 5),
            //            data: this.dataAll,
          });
          this.search();
        }, 1500);
      } else if (type === 2) {
        this.$refs.table.exportCsv({
          filename: '排序和过滤后的数据',
          original: false,
          quoted: true
        });
      }
    },
    onCurrentChange (params1, params2) {
      this.$emit('on-current-change', params1, params2);
    },
    onSelect (params1, params2) {
      this.selectRows = params1;
      this.$emit('on-select', params1, params2);
    },
    onSelectCancel (params1, params2) {
      this.selectRows = params1;
      this.$emit('on-select-cancel', params1, params2);
    },
    onSelectAll (params1, params2) {
      this.selectRows = params1;
      this.$emit('on-select-all', params1, params2);
    },
    onSelectAllCancel (params1, params2) {
      this.selectRows = params1;
      this.$emit('on-select-all-cancel', params1, params2);
    },
    onSelectionChange (params1, params2) {
      this.$emit('on-selection-change', params1, params2);
    },
    onSortChange (params1, params2, params3) {
      this.$emit('on-sort-change', params1, params2, params3);
    },
    onFilterChange (params1) {
      this.$emit('on-filter-change', params1);
    },
    onRowClick (params1, params2) {
      this.$emit('on-row-click', params1, params2);
    },
    onRowDblclick (params1, params2, params3) {
      this.$emit('on-row-dblclick', params1, params2);
    },
    onExpand (params1, params2, params3) {
      this.$emit('on-expand', params1, params2);
    },
    exportCsv (config) {
      this.$refs['table'].exportCsv(config);
    },
    clearCurrentRow () {
      this.$refs['table'].clearCurrentRow();
    },
    changeSize (current) {
      this.pagedata.pagesize = current;
      if (this.pager) {
        if (this.front) {
        }
        if (this.back) {
          this.$emit('page-change', this.pagedata);
        }
      }
    },
    // 改变页码
    changePage (current) {
      // 这里直接更改了模拟的数据，真实使用场景应该从服务端获取数据
      // this.current = current;
      if (this.pager) {
        if (this.front) {
          this.pagedata.current = current;
        } else {
          this.pagedata.current = current;
          // console.log(this.pagedata)
          this.$emit('page-change', this.pagedata);
        }
      }
    },
    refresh () {
      this.$emit('refresh', this.pagedata);
    },
    search () {
      this.$emit('refresh', this.searchKey, this.pagedata);
    }
  },
  mounted () {
    this.columnList = deepCopy(this.columns);

    // console.log(this.labels);
    if (this.op) {
      let opobj = {
        title: '操作',
        key: 'action',
        width: 150,
        align: 'center',
        render: (h, params) => {
          return h('div', [
            h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small',
                  disabled: !checkAccess(this.operateLabels, 'Event', 'update')
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.emit('update', [params.row]);
                  }
                }
              },
              '修改'
            ),
            h(
              'Button',
              {
                props: {
                  type: 'error',
                  size: 'small',
                  disabled: !checkAccess(this.operateLabels, 'Event', 'delete')
                },
                on: {
                  click: () => {
                    this.emit('delete', [params.row]);
                  }
                }
              },
              '删除'
            )
          ]);
        }
      };
      // this.formatColumns = JSON.parse(JSON.stringify(this.columns)).push(op);
      this.columnList.push(opobj);
    }
    if (this.ck) {
      let ckobj = {
        type: 'selection',
        width: 50
        // align: 'center'
      };
      this.columnList.unshift(ckobj);
    }
  }
};
</script>

<style scoped>
.table-container {
  margin: 0;
  padding: 0;
}

.table-operation {
  margin-bottom: 5px;
}

.btn-list {
  display: inline;
  margin-bottom: 5px;
}

.table {
  /* border-radius: 15px; */
}
</style>
